package de.fuberlin.dbs.wm;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import de.fuberlin.dbs.wm.dao.Dao;
import de.fuberlin.dbs.wm.dao.TournamentDao;
import de.fuberlin.dbs.wm.dao.util.DatabaseSource;
import de.fuberlin.dbs.wm.util.FreemarkerParser;
import de.fuberlin.dbs.wm.util.NotAllowedException;

import freemarker.template.TemplateException;

public class S_TopThree extends HttpServlet {	
	private static final long serialVersionUID = 4646599090007574512L;
	private final String template = "t_topThree.ftl";
	private PrintWriter print;
	@SuppressWarnings("rawtypes")
	private Map datamodel;
	private String tournament;

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		print = response.getWriter();
		datamodel = new HashMap();
		tournament = request.getParameter("tournament");
		
		try {
			/*Connect to the Oracle Database*/			
			DatabaseSource.setUpConnection();				
			
			setUp();
			
			/*Send the datamodel to the template to be printed in the browser*/
			new FreemarkerParser(template).freemarkerDo(print, datamodel, this.getServletContext());
		} catch (SQLException e) {
			datamodel.put("con_error", "Konnte sich nicht mit der Datenbank verbinden");
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		} finally {
			try {
				DatabaseSource.closeConnection();
			} catch (SQLException e) {
				System.err.println("Could not close Connection");
			} catch (NullPointerException e) {
				System.err.println("Connection could not be closed for not having opened");
			}
		}	
	}
	
	@SuppressWarnings("unchecked")
	private void setUp() {
		new Dao();		
		try {
			datamodel.put("teams", TournamentDao.weAreTheChampions(tournament));
			datamodel.put("tournament", tournament);
		} catch (NotAllowedException e) {
			datamodel.put("warning", "Nicht berechtigt dieses Turnier zu betrachten!");
		} catch (Exception e) {
			datamodel.put("warning", "Das Turnier ist noch nicht beendet");
		}
		
	}
}
